package services

import (
	"backend/common"
	"backend/config"
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Run() {
	// 设置debug模式
	if !config.Configs.Debug {
		gin.SetMode(gin.ReleaseMode)
	}

	// 实例化gin引擎
	engine := gin.New()

	gin.DisableConsoleColor()
	engine.Use(gin.Logger())

	//初始化数据库
	_, err := common.InitDB()
	if err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}

	// 初始化Redis
	_, err = common.InitRedis()
	if err != nil {
		log.Fatalf("Failed to initialize Redis: %v", err)
	}
	defer func() {
		if err := common.CloseRedis(); err != nil {
			log.Printf("Error closing Redis connection: %v", err)
		}
	}()

	// CORS
	engine.Use(func(ctx *gin.Context) {
		ctx.Header("Access-Control-Allow-Origin", "*")
		ctx.Header("Access-Control-Allow-Credentials", "true")
		ctx.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
		if ctx.Request.Method == http.MethodOptions {
			ctx.Status(http.StatusOK)
			ctx.Abort()
		}
	})

	// app routers
	CollectRoutes(engine)

	// start server
	engine.Run(fmt.Sprintf("0.0.0.0:%d", config.Configs.Port))
}
